<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(B卷,200分)- 区间交集（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述 </h4> 
<p>给定一组闭区间&#xff0c;其中部分区间存在交集。</p> 
<p>任意两个给定区间的交集&#xff0c;称为公共区间(如:[1,2],[2,3]的公共区间为[2,2]&#xff0c;[3,5],[3,6]的公共区间为[3,5])。</p> 
<p>公共区间之间若存在交集&#xff0c;则需要合并(如:[1,3],[3,5]区间存在交集[3,3]&#xff0c;需合并为[1,5])。</p> 
<p>按升序排列输出合并后的区间列表。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>一组区间列表&#xff0c;</p> 
<p>区间数为 N: 0&lt;&#61;N&lt;&#61;1000;</p> 
<p>区间元素为 X: -10000&lt;&#61;X&lt;&#61;10000。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>升序排列的合并区间列表</p> 
<p></p> 
<h4><strong>备注</strong></h4> 
<ul><li>区间元素均为数字&#xff0c;不考虑字母、符号等异常输入。</li><li>单个区间认定为无公共区间。</li></ul> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">4<br /> 0 3<br /> 1 3<br /> 3 5<br /> 3 6</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">1 5</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;"> <p>[0,3]和[1,3]的公共区间为[1,3]&#xff0c;</p> <p>[0,3]和[3,5]的公共区间为[3,3]&#xff0c;</p> <p>[0,3]和[3,6]的公共区间为[3,3]&#xff0c;</p> <p>[1,3]和[3,5]的公共区间为[3,3]&#xff0c;</p> <p>[1,3]和[3,6]的公共区间为[3,3]&#xff0c;</p> <p>[3,5]和[3,6]的公共区间为[3,5]&#xff0c;</p> <p>公共区间列表为[[1,3],[3,3],[3,5]]&#xff1b;</p> <p>[1,3],[3,3],[3,5]存在交集&#xff0c;须合并为[1,5]。</p> </td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;"> <p>4<br /> 0 3<br /> 1 4<br /> 4 7<br /> 5 8</p> </td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">1 3<br /> 4 4 <br /> 5 7</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;"> <p>2<br /> 1 2<br /> 3 4</p> </td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">None</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">[1,2]和[3,4]无交集</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题主要考察&#xff1a;区间交集求解、以及区间合并。</p> 
<p></p> 
<p>首先&#xff0c;我们要求解输入的多个区间中&#xff0c;任意两个区间的交集&#xff08;公共区间&#xff09;。</p> 
<p>然后&#xff0c;将这些公共区间进行合并后打印。</p> 
<p></p> 
<p>两个区间的交集求解思路如下&#xff1a;</p> 
<p>将两个区间按照开始位置进行升序&#xff0c;假设排序后&#xff0c;两个区间顺序是&#xff1a;[[s1, e1]&#xff0c;[s2, e2]]</p> 
<p>那么必然 s1 &lt;&#61; s2&#xff0c;因此如果存在交集的话&#xff0c;即e1 &gt;&#61; s2</p> 
<p>则交集的左边界必然是s2&#xff0c;而交集的右边界取值Math.min(e1, e2) </p> 
<p></p> 
<p>区间合并的逻辑可以参考&#xff1a;<a href="https://blog.csdn.net/qfc_128220/article/details/127341822?ops_request_misc&#61;%257B%2522request%255Fid%2522%253A%2522166869739016782425184109%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&amp;request_id&#61;166869739016782425184109&amp;biz_id&#61;0&amp;utm_medium&#61;distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-127341822-null-null.nonecase&amp;utm_term&#61;%E8%B7%AF%E7%81%AF&amp;spm&#61;1018.2226.3001.4450" title="华为机试 - 路灯照明问题_伏城之外的博客-CSDN博客">华为机试 - 路灯照明问题_伏城之外的博客-CSDN博客</a></p> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; sc.nextInt();

    int[][] ranges &#61; new int[n][2];
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      ranges[i][0] &#61; sc.nextInt();
      ranges[i][1] &#61; sc.nextInt();
    }

    getResult(n, ranges);
  }

  public static void getResult(int n, int[][] ranges) {
    // 区间按照开始位置升序
    Arrays.sort(ranges, (a, b) -&gt; a[0] - b[0]);

    // combine用于保存交集
    ArrayList&lt;int[]&gt; combine &#61; new ArrayList&lt;&gt;();

    // 求任意两个区间之间的交集
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      int s1 &#61; ranges[i][0], e1 &#61; ranges[i][1];
      for (int j &#61; i &#43; 1; j &lt; n; j&#43;&#43;) {
        int s2 &#61; ranges[j][0], e2 &#61; ranges[j][1];
        if (s2 &lt;&#61; e1) {
          combine.add(new int[] {s2, Math.min(e1, e2)});
        } else {
          // 由于ranges已经升序&#xff0c;因此如果ranges[i]和ranges[j]没有交集的话&#xff0c;则也不可能和ranges[j&#43;1]区间有交集
          break;
        }
      }
    }

    if (combine.size() &#61;&#61; 0) {
      System.out.println(&#34;None&#34;);
      return;
    }

    // 合并公共区间
    combine.sort((a, b) -&gt; a[0] !&#61; b[0] ? a[0] - b[0] : b[1] - a[1]);

    int[] pre &#61; combine.get(0);
    for (int i &#61; 1; i &lt; combine.size(); i&#43;&#43;) {
      int[] cur &#61; combine.get(i);

      if (pre[1] &gt;&#61; cur[0]) {
        pre[1] &#61; Math.max(cur[1], pre[1]);
      } else {
        System.out.println(pre[0] &#43; &#34; &#34; &#43; pre[1]);
        pre &#61; cur;
      }
    }

    System.out.println(pre[0] &#43; &#34; &#34; &#43; pre[1]);
  }
}
</code></pre> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 1) {
    n &#61; parseInt(lines[0]);

    if (n &#61;&#61; 0) {
      console.log(&#34;None&#34;);
      lines.length &#61; 0;
    }
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n &#43; 1) {
    lines.shift();
    const ranges &#61; lines.map((line) &#61;&gt; line.split(&#34; &#34;).map(Number));

    getResult(ranges);

    lines.length &#61; 0;
  }
});

function getResult(ranges) {
  // 区间按照开始位置升序
  ranges.sort((a, b) &#61;&gt; a[0] - b[0]);

  // combine用于保存交集
  const combine &#61; [];

  // 公共区间求解
  for (let i &#61; 0; i &lt; ranges.length; i&#43;&#43;) {
    const [s1, e1] &#61; ranges[i];
    for (let j &#61; i &#43; 1; j &lt; ranges.length; j&#43;&#43;) {
      const [s2, e2] &#61; ranges[j];
      if (s2 &lt;&#61; e1) {
        combine.push([s2, Math.min(e1, e2)]);
      } else {
        // 由于ranges已经升序&#xff0c;因此如果ranges[i]和ranges[j]没有交集的话&#xff0c;则也不可能和ranges[j&#43;1]区间有交集
        break;
      }
    }
  }

  if (combine.length &#61;&#61; 0) return console.log(&#34;None&#34;);

  // 合并公共区间
  combine.sort((a, b) &#61;&gt; (a[0] !&#61; b[0] ? a[0] - b[0] : b[1] - a[1]));

  let pre &#61; combine[0];
  for (let i &#61; 1; i &lt; combine.length; i&#43;&#43;) {
    const cur &#61; combine[i];

    if (pre[1] &gt;&#61; cur[0]) {
      pre[1] &#61; Math.max(cur[1], pre[1]);
    } else {
      console.log(pre.join(&#34; &#34;));
      pre &#61; cur;
    }
  }

  console.log(pre.join(&#34; &#34;));
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
n &#61; int(input())
ranges &#61; [list(map(int, input().split())) for _ in range(n)]


# 算法入口
def getResult():
    # 区间按照开始位置升序
    ranges.sort(key&#61;lambda x: x[0])

    # combine用于保存公共区间
    combine &#61; []

    for i in range(n):
        s1, e1 &#61; ranges[i]
        for j in range(i &#43; 1, n):
            s2, e2 &#61; ranges[j]
            if s2 &lt;&#61; e1:
                combine.append([s2, min(e1, e2)])
            else:
                # 由于ranges已经升序&#xff0c;因此如果ranges[i]和ranges[j]没有交集的话&#xff0c;则也不可能和ranges[j&#43;1]区间有交集
                break

    if len(combine) &#61;&#61; 0:
        print(&#34;None&#34;)
        return

    # 合并公共区间
    combine.sort(key&#61;lambda x: (x[0], -x[1]))

    pre &#61; combine[0]
    for i in range(1, len(combine)):
        cur &#61; combine[i]

        if pre[1] &gt;&#61; cur[0]:
            pre[1] &#61; max(cur[1], pre[1])
        else:
            print(&#34; &#34;.join(map(str, pre)))
            pre &#61; cur

    print(&#34; &#34;.join(map(str, pre)))


# 算法调用
getResult()
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>